package request

import (
	"github.com/go-playground/validator/v10"
)

// 自定义验证失败消息

// Filed.Tag: error
type ValidatorMessages map[string]string

type Validator interface {
	GetMessages() ValidatorMessages
}

// GetErrorMsg 获取表单验证的错误信息
func GetErrorMsg(request interface{}, err error) string {
	if validtionErrs, isErr := err.(validator.ValidationErrors); isErr {
		reqValid, isValidator := request.(Validator)
		for _, fieldErr := range validtionErrs {
			if isValidator {
				key := fieldErr.Field() + "." + fieldErr.Tag()
				// debug
				// global.App.Log.Info("key:" + key)
				message, exist := reqValid.GetMessages()[key]
				if exist {
					return message
				}
			}
			return fieldErr.Error()
		}
	}
	return "Parameter Error"
}
